package com.ibeetl.codestory.core.ctx;

import com.ibeetl.codestory.core.action.Action;
import com.ibeetl.codestory.core.ast.Ast;
import com.ibeetl.codestory.core.issue.Issue;
import com.ibeetl.codestory.core.issue.LogHandler;
import com.ibeetl.codestory.core.ast.AstType;


import java.util.*;

public class BaseContext  implements  Context{
	Map<AstType, Set<Action>> typeActionMap = Collections.synchronizedMap(new HashMap<AstType, Set<Action>>());
	List<LogHandler> logHandlers = new ArrayList<>();
	@Override
	public void register(AstType type, Action action) {
		Set<Action> actions = typeActionMap.getOrDefault(type,new TreeSet<Action>());
		actions.add(action);
	}


	@Override
	public void registerLogHandler(LogHandler handler) {
		logHandlers.add(handler);
	}


	@Override
	public void onAction(Ast ast) {
		AstType type = ast.getAstType();
		Set<Action> set = typeActionMap.get(type);
		if(set==null){
			return;
		}
		for(Action action:set){
			action.on(ast,this);
		}
	}

	@Override
	public void log(Issue issue) {
		if(logHandlers.size()==1){
			logHandlers.get(0).acceptLog(issue);
		}else{
			for(LogHandler logHandler:logHandlers){
				logHandler.acceptLog(issue);
			}
		}

	}
}
